package com.example.note2;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;  // 导入 Log 类
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    private EditText username, password;
    private Button loginButton;
    private TextView registerText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        loginButton = findViewById(R.id.login_button);
        registerText = findViewById(R.id.register_text);

        loginButton.setOnClickListener(v -> login());
        registerText.setOnClickListener(v -> openRegisterActivity());
    }

    private void login() {
        String usernameInput = username.getText().toString().trim();
        String passwordInput = password.getText().toString().trim();

        CRUD crud = new CRUD(this);
        crud.open();

        try {
            boolean isValidUser = crud.authenticateUser(usernameInput, passwordInput);

            if (isValidUser) {
                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                Log.d("LoginActivity", "用户登录用户名: " + usernameInput);
                long userId = crud.getUserIdByUsername(usernameInput);
                Log.d("LoginActivity","用户登录用户名: " + userId);
                // 登录成功后跳转到主界面
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra("username", usernameInput); // 传id

                startActivity(intent);
            } else {
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e("LoginActivity", "登录失败", e);
            Toast.makeText(this, "登录处理出现错误", Toast.LENGTH_SHORT).show();
        } finally {
            crud.close();
        }
    }


    private void openRegisterActivity() {
        Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
        startActivity(intent);
    }
}
